package com.law.lawcaculator.service.impl;

import com.law.lawcaculator.mapper.QuestionOptionsRelationMapper;
import com.law.lawcaculator.model.dto.NextFormResponse;
import com.law.lawcaculator.model.entity.QuestionOptionsRelation;
import com.law.lawcaculator.model.entity.SubmitAnswers;
import com.law.lawcaculator.service.FormService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FormServiceImpl implements FormService {

    private final QuestionOptionsRelationMapper questionOptionsRelationMapper;

    @Override
    public NextFormResponse generateNextForm(String sessionId, List<SubmitAnswers> answers) {
        List<Map<String, Object>> nextQuestions = new ArrayList<>();
        List<Map<String, Object>> nextOptions = new ArrayList<>();

        // 1. 分析用户已选择的答案
        Map<Long, String> userSelections = new HashMap<>();
        Map<String, String> userInputs = new HashMap<>();

        for (SubmitAnswers answer : answers) {
            if (answer.getOptionId() != null) {
                userSelections.put(answer.getQuestionId(), answer.getOptionId().toString());
            }
            if (answer.getAnswer() != null) {
                userInputs.put(answer.getQuestionId().toString(), answer.getAnswer());
            }
        }

        // 2. 根据已选内容，查找关联的后续问题
        // 这里简化处理，实际应该从question_options_relation查找
        // 例如：如果用户选择了地区=北京，追加社保政策相关问题
        boolean hasSelectedBeijing = userSelections.values().stream().anyMatch(v -> v.contains("beijing")) ||
                userInputs.values().stream().anyMatch(v -> v.contains("北京"));

        if (hasSelectedBeijing) {
            // 添加北京地区特有的问题
            nextQuestions.add(Map.of(
                    "questionId", "beijing_social_insurance",
                    "label", "是否享受本地社保政策",
                    "type", "radio"
            ));
            nextOptions.add(Map.of("optionId", "opt_has_insurance", "label", "是"));
            nextOptions.add(Map.of("optionId", "opt_no_insurance", "label", "否"));
        }

        // 3. 检查是否需要工资详情
        boolean hasSalaryInput = userInputs.values().stream().anyMatch(v -> {
            try {
                Double.parseDouble(v);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        });

        if (hasSalaryInput && nextQuestions.isEmpty()) {
            nextQuestions.add(Map.of(
                    "questionId", "salary_detail",
                    "label", "请补充说明工资构成",
                    "type", "text"
            ));
        }

        return new NextFormResponse(nextQuestions, nextOptions);
    }
}